package com.lyy.common.advice;

import com.lyy.common.utils.ResultInfo;
import com.lyy.common.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author YW
 * @since 2019-12-25
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    /**
     * 处理参数异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public Map<String, Object> exceptionHandlerParamsException(IllegalArgumentException e) {
        return ResultUtils.getResult(ResultInfo.PARAME_EMPTY, e.getMessage());
    }

    /**
     * shiro权限异常处理
     *
     * @return result
     */
    @ResponseBody
    @ExceptionHandler(AuthorizationException.class)
    public Map<String, Object> handleShiroException(AuthorizationException authorizationException) {
        log.error("shiro权限异常", authorizationException);
        return ResultUtils.getResult(ResultInfo.FORBIDDEN_ERROR);
    }


    /**
     * token无效异常
     */
    @ResponseBody
    @ExceptionHandler(IncorrectCredentialsException.class)
    public Map<String, Object> handleTokenException(IncorrectCredentialsException incorrectCredentialsException) {
        log.error("token无效异常", incorrectCredentialsException);
        return ResultUtils.getResult(ResultInfo.TOKEN_ERROR);
    }


    /**
     * 参数校验异常处理
     *
     * @return result
     */
    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Map<String, Object> handleMissingParameterException(MissingServletRequestParameterException missingServletRequestParameterException) {
        log.error("参数校验异常", missingServletRequestParameterException);
        return ResultUtils.getResult(ResultInfo.MISSING_PARAMS);
    }

    /**
     * 数字格式化异常处理
     *
     * @return result
     */
    @ResponseBody
    @ExceptionHandler(NumberFormatException.class)
    public Map<String, Object> handleNumberFormatException(NumberFormatException numberFormatException) {
        log.error("数字格式化异常", numberFormatException);
        return ResultUtils.getResult(ResultInfo.NUMBER_FORMAT_EXCEPTION);
    }


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> exceptionHandler(Exception e) {
        log.error("未知异常！原因是:", e);
        return ResultUtils.getResult(ResultInfo.SERVER_INTERNAL_EXCEPTION);
    }

}